package at.fhv.androideightpuzzle.network.messageparsers;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import at.fhv.androideightpuzzle.network.message.GameResultMessage;
import at.fhv.androideightpuzzle.network.message.IMessage;

public class GameResultMessageParser implements IMessageParser{
	
	public GameResultMessageParser(){
		//
	}
	
	public IMessage parseMessage(String message){
		try{
			JSONParser parser=new JSONParser();
			JSONObject jsonObj=(JSONObject)parser.parse(message);
			
			return parseMessage(jsonObj);
		}catch(Exception exc){
			android.util.Log.e("GameResultMessageParser",exc.getMessage(),exc);
			
			return null;
		}
	}
	
	public IMessage parseMessage(JSONObject jsonObj){
		try{
			JSONObject payload=(JSONObject) jsonObj.get("payload");
			
			JSONArray namesJsonArr=(JSONArray)payload.get("players");
			JSONArray durationsJsonArr=(JSONArray)payload.get("durations");
			
			String[] names=new String[namesJsonArr.size()];
			long[] durations=new long[durationsJsonArr.size()];
			
			for(int i=0; i<names.length; i++){
				names[i]=(String)namesJsonArr.get(i);
			}
			
			for(int i=0; i<durations.length; i++){
				durations[i]=((Number)durationsJsonArr.get(i)).longValue();
			}
			
			return new GameResultMessage(names,durations);
		}catch(Exception exc) {
			android.util.Log.e("GameResultMessageParser",exc.getMessage(),exc);
			
			return null;
		}
	}
}
